import React, { useState, useEffect } from 'react';
import TitleBack from "../../components/TitleBack/TitleBack";
import { reqgetcate, reqgetgoods } from '../../http/api';
import { NavLink } from 'react-router-dom';
import "./Cate.less";

export default function Cate() {
    const [cate, setcate] = useState([]);
    const [goods, setgoods] = useState([]);
    const [n, setN] = useState(0);

    useEffect(async () => {
        let res1 = await reqgetcate();
        if (res1.data.code === 200) {
            setcate(res1.data.list)
        }

        let res2 = await reqgetgoods({ fid: 1 });
        if (res2.data.code === 200) {
            setgoods(res2.data.list.length > 0 ? res2.data.list : [])
        }
    }, [])

    function changeN(index, id) {
        setN(index);
        console.log(id);
        reqgetgoods({ fid: id }).then(res => {
            if (res.data.code === 200) {
                setgoods(res.data.list.length > 0 ? res.data.list : [])
            }
        })
    }
    console.log(goods);
    return (
        <div className="cate">
            <TitleBack title={"商品分类"}></TitleBack>
            {/* 分类遍历 */}
            <ul className="catenav">
                {
                    cate.map((item, index) => {
                        return <li key={item.id} className={index === n ? 'active' : ''} onClick={() => changeN(index, item.id)}>{item.catename}</li>
                    })
                }
            </ul>
            <ul className="goods">
                {
                    goods.map((item, index) => {
                        return (
                            <NavLink to={"/detail/"+item.id+"/1"} key = { item.id } >
                                <li className="bd-items">
                                    <img src={item.img} alt="" />
                                    <h3>{item.goodsname}</h3>
                                    <p className="description">{item.description}</p>
                                    <p className="price">&yen; <b>{item.price}</b><i>&yen; {item.market_price}</i></p>
                                </li>
                            </NavLink>
                        )
                    })
                }
        </ul>
        </div >
    )
}
